Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

Solution:

  1. public class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. if (strs == null || strs.length == 0) {
  4. return "";
  5. }
  6. for (int i = 0; i < strs[0].length(); i++) {
  7. for (int j = 1; j < strs.length; j++) {
  8. if (i >= strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i)) {
  9. return strs[0].substring(0, i);
  10. }
  11. }
  12. }
  13. return strs[0];
  14. }
  15. }